package com.ruoyi.common.qy.utils;

public class SnowflakeUtils {
    private static volatile SnowflakeIdGenerator instance;

    private SnowflakeUtils() {
        // 私有构造器
    }

    public static SnowflakeIdGenerator getInstance() {
        if (instance == null) {
            synchronized (SnowflakeUtils.class) {
                if (instance == null) {
                    // 从环境变量或配置文件中获取，默认使用1,1
                    long datacenterId = Long.parseLong(
                        System.getProperty("snowflake.datacenter.id", "1"));
                    long workerId = Long.parseLong(
                        System.getProperty("snowflake.worker.id", "1"));
                    instance = new SnowflakeIdGenerator(datacenterId, workerId);
                }
            }
        }
        return instance;
    }

    public static long nextId() {
        return getInstance().nextId();
    }

    // 生成字符串形式的ID（Base62编码，更短）
    public static String nextIdString() {
        return toBase62(nextId());
    }

    private static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private static String toBase62(long num) {
        StringBuilder sb = new StringBuilder();
        while (num > 0) {
            sb.insert(0, BASE62.charAt((int) (num % 62)));
            num = num / 62;
        }
        return sb.toString();
    }
}
